package com.cfc.stage1;

import common.ListNode;
import org.junit.Test;

/**
 * @description:
 * @author: yangxuan10
 * @create: 2024-04-09 14:22
 **/
public class MergeTwoLists {


    @Test
    public void test1() {

        ListNode list1 = new ListNode(1);
        list1.next = new ListNode(2);

        ListNode list2 = new ListNode(3);
        list2.next = new ListNode(4);


        ListNode listNode = mergeTwoLists(list1, list2);
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        } else if (l2 == null) {
            return l1;
        } else if (l1.val < l2.val) {
            ListNode listNode = mergeTwoLists(l1.next, l2);
            l1.next = listNode;
            return l1;
        } else {
            ListNode listNode = mergeTwoLists(l1, l2.next);
            l2.next = listNode;
            return l2;
        }
    }

    public ListNode mergeTwoLists1(ListNode list1, ListNode list2) {

        ListNode newNode = new ListNode();
        ListNode currentNode = newNode;

        while (true) {
            if (list1 == null && list2 == null) {
                break;
            }
            if (list1 == null && list2 != null) {
                currentNode.next = list2;
                break;
            }
            if (list1 != null && list2 == null) {
                currentNode.next = list1;
                break;
            }
            int integer1 = list1.val;
            int integer2 = list2.val;
            if (integer1 <= integer2) {
                ListNode listNode = new ListNode(integer1);
                currentNode.next = listNode;
                currentNode = currentNode.next;
                list1 = list1.next;
            } else {
                ListNode listNode = new ListNode(integer2);
                currentNode.next = listNode;
                currentNode = currentNode.next;
                list2 = list2.next;
            }
        }
        System.out.println(newNode.next);
        return newNode.next;
    }
}